package org.dromara.run.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.dromara.basic.domain.vo.MemberVo;
import org.dromara.basic.service.IMemberService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.run.domain.bo.RuleBo;
import org.dromara.run.domain.bo.ScoreBo;
import org.dromara.run.domain.vo.RuleVo;
import org.dromara.run.domain.vo.ScheduleVo;
import org.dromara.run.domain.vo.ScoreVo;
import org.dromara.run.service.*;
import org.springframework.stereotype.Service;
import org.dromara.run.domain.bo.RecordBo;
import org.dromara.run.domain.vo.RecordVo;
import org.dromara.run.domain.Record;
import org.dromara.run.mapper.RecordMapper;

import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 阳光跑跑步记录表Service业务层处理
 *
 * @author chl
 * @date 2024-08-30
 */
@RequiredArgsConstructor
@Service
public class RecordServiceImpl implements IRecordService {

    private final RecordMapper baseMapper;

    private final IScheduleService scheduleService;

    private final IRuleService ruleService;

    private final IScoreService scoreService;

    private final IScoreConfigService scoreConfigService;

    private final IMemberService memberService;

    /**
     * 查询阳光跑跑步记录表
     */
    @Override
    public RecordVo queryById(Long recordId){
        return baseMapper.selectVoById(recordId);
    }

    /**
     * 查询阳光跑跑步记录表列表
     */
    @Override
    public TableDataInfo<RecordVo> queryPageList(RecordBo bo, PageQuery pageQuery) {
        QueryWrapper<Record> lqw = buildQueryWrapper(bo);
        Page<RecordVo> result = baseMapper.selectRecordList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询阳光跑跑步记录表列表
     */
    @Override
    public List<RecordVo> queryList(RecordBo bo) {
        QueryWrapper<Record> lqw = buildQueryWrapper(bo);
        return baseMapper.selectRecordList(lqw);
    }

    private QueryWrapper<Record> buildQueryWrapper(RecordBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<Record> lqw = new QueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getScheduleId()), "prr.schedule_id", bo.getScheduleId());
        lqw.eq(bo.getRecordId()!=null, "prr.record_id", bo.getRecordId());
        lqw.eq(StringUtils.isNotBlank(bo.getMemberId()), "prr.member_id ", bo.getMemberId());
        lqw.eq(bo.getUploadTime() != null, "", bo.getUploadTime());
        lqw.between(params.get("beginUploadTime") != null && params.get("endUploadTime") != null,
            "prr.upload_time" ,params.get("beginUploadTime"), params.get("endUploadTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getRecordType()), "prr.record_type", bo.getRecordType());
        lqw.like(StringUtils.isNotBlank(bo.getStudentName()), "pmi.name", bo.getStudentName());
        lqw.eq(StringUtils.isNotBlank(bo.getYears()), "pbtc.years", bo.getYears());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), "pmi.gender", bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getClassId()), "pmi.class_id", bo.getClassId());
        lqw.eq(StringUtils.isNotBlank(bo.getProfessionalId()), "sd1.dept_id", bo.getProfessionalId());
        lqw.eq(StringUtils.isNotBlank(bo.getCollegeId()), "sd2.dept_id", bo.getCollegeId());
        return lqw;
    }

    /**
     * 新增阳光跑跑步记录表
     */
    @Override
    public Boolean insertByBo(RecordBo bo) throws ParseException {
        ScheduleVo scheduleVo = scheduleService.queryById(Long.parseLong(bo.getScheduleId()));
        MemberVo memberVo = memberService.queryByIdNumber(bo.getMemberId());
        ScoreBo scoreBo=new ScoreBo();
        scoreBo.setScheduleId(bo.getScheduleId());
        scoreBo.setMemberId(bo.getMemberId());
        ScoreVo scoreVo = scoreService.selectScoreInfo(scoreBo);

        if (ObjectUtils.isNotEmpty(scheduleVo)&&ObjectUtils.isNotEmpty(memberVo)&&ObjectUtils.isNotEmpty(scoreVo)) {
            List<RuleVo> ruleVos =new ArrayList<>();
            if(StringUtils.isNotEmpty(scheduleVo.getRuleId())){
                List<Long> ruleIds = Arrays.stream(scheduleVo.getRuleId().split(",")).map(Long::parseLong).collect(Collectors.toList());
                RuleBo ruleBo=new RuleBo();
                ruleBo.setIds(ruleIds);
                ruleVos = ruleService.queryList(ruleBo);
            }

            for (RuleVo rule:ruleVos) {
                if(memberVo.getGender()==rule.getGender()){
                    SimpleDateFormat dateFormat1 = new SimpleDateFormat( "yyyy-MM-dd");
                    SimpleDateFormat dateFormat2 = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
                    long ruleTimeBegin = rule.getRuleTimeBegin().getTime();
                    long ruleTimeEnd = rule.getRuleTimeEnd().getTime();
                    Date startTime = bo.getStartTime();
                    Date endTime = bo.getEndTime();
                    String startTimeString = dateFormat2.format(startTime).split(" ")[1];
                    String endTimeString = dateFormat2.format(endTime).split(" ")[1];
                    long  startTimeL=Time.valueOf(startTimeString).getTime();
                    long  endTimeL=Time.valueOf(endTimeString).getTime();
                    long extraRunTimeBegin = rule.getExtraRunTimeBegin().getTime();
                    long extraRunTimeEnd = rule.getExtraRunTimeEnd().getTime();
                    long morningRunTimeBegin = rule.getMorningRunTimeBegin().getTime();
                    long morningRunTimeEnd = rule.getMorningRunTimeEnd().getTime();
                    long extraStandardBegin =Time.valueOf(rule.getExtraStandardBegin()).getTime() ;
                    long extraStandardEnd = Time.valueOf(rule.getExtraStandardEnd()).getTime();
                    long morningStandardBegin =Time.valueOf(rule.getMorningStandardBegin()).getTime() ;
                    long morningStandardEnd = Time.valueOf(rule.getMorningStandardEnd()).getTime();
                    long pace = Time.valueOf(bo.getPace()).getTime();
                    if((bo.getStartTime().getTime()>=ruleTimeBegin&&bo.getStartTime().getTime()<=ruleTimeEnd)&&
                        (bo.getEndTime().getTime()>=ruleTimeBegin&&bo.getEndTime().getTime()<=ruleTimeEnd)
                    ){
                        if((startTimeL>=extraRunTimeBegin&&startTimeL<=extraRunTimeEnd)&&
                            (endTimeL>=extraRunTimeBegin&&endTimeL<=extraRunTimeEnd)){
                            if(pace>=extraStandardBegin&&pace<=extraStandardEnd){

                            }else {
                                bo.setDescription("配速不合格，跑步记录无效");
                                bo.setRecordType("1");
                            }

                        }else if((morningRunTimeBegin>=extraRunTimeBegin&&morningRunTimeBegin<=extraRunTimeEnd)&&
                            (morningRunTimeEnd>=extraRunTimeBegin&&morningRunTimeEnd<=extraRunTimeEnd)){
                            if(pace>=morningStandardBegin&&pace<=morningStandardEnd){

                            }else {
                                bo.setDescription("配速不合格，跑步记录无效");
                                bo.setRecordType("1");
                            }
                        }else {
                            bo.setDescription("跑步时间没有在规定时间内，跑步记录无效");
                            bo.setRecordType("1");
                        }

                    }
                }
            }
        }
        Record add = MapstructUtils.convert(bo, Record.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRecordId(add.getRecordId());
        }
        return flag;
    }

    /**
     * 修改阳光跑跑步记录表
     */
    @Override
    public Boolean updateByBo(RecordBo bo) {

        Record update = MapstructUtils.convert(bo, Record.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Record entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除阳光跑跑步记录表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
